/*
 * Copyright (C) 2014 Lucid Wolf
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.lucidhex;


import com.lucidhex.erfworld.ErfWorldDefaultTemplate;
import com.lucidhex.hex.LucidHexType;
import com.lucidhex.io.LucidWorldParser;
import com.lucidhex.viewer.mapimport.MaptoHexImport;
import java.awt.Graphics;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author Wolf
 */
public class GameMasterView extends javax.swing.JFrame {

    /**
     * Creates new form GameMasterView
     */
    LucidWorld world = null;
    File xmlFile = null;
    public GameMasterView() {
        world = new LucidWorld();
        initComponents();  
        viewPortal.setErf(world);
        viewPortal.setTextOut(textOut);
        viewPortal.getViewOptions().reset();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        split1 = new javax.swing.JSplitPane();
        split2 = new javax.swing.JSplitPane();
        treeScroll = new javax.swing.JScrollPane();
        sideTree = new javax.swing.JTree();
        txtScroll = new javax.swing.JScrollPane();
        sideText = new javax.swing.JTextArea();
        viewPortal = new com.lucidhex.viewer.ViewPortal();
        textOut = new javax.swing.JTextField();
        menuBar = new javax.swing.JMenuBar();
        file_Menu = new javax.swing.JMenu();
        file_new = new javax.swing.JMenuItem();
        file_open = new javax.swing.JMenuItem();
        file_save = new javax.swing.JMenuItem();
        file_saveAs = new javax.swing.JMenuItem();
        file_exportPNG = new javax.swing.JMenuItem();
        file_exit = new javax.swing.JMenuItem();
        edit_Menu = new javax.swing.JMenu();
        edit_addHexsToRadius = new javax.swing.JMenuItem();
        edit_addHexByPicture = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jSplitPane1.setDividerLocation(460);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPane1.setResizeWeight(1.0);

        split1.setDividerLocation(200);

        split2.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        split2.setResizeWeight(0.5);

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("Gobwin Knob");
        javax.swing.tree.DefaultMutableTreeNode treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Stacks");
        javax.swing.tree.DefaultMutableTreeNode treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("Wanda's Stack");
        javax.swing.tree.DefaultMutableTreeNode treeNode4 = new javax.swing.tree.DefaultMutableTreeNode("Red Dwagon");
        javax.swing.tree.DefaultMutableTreeNode treeNode5 = new javax.swing.tree.DefaultMutableTreeNode("Wanda (lead)");
        treeNode4.add(treeNode5);
        treeNode3.add(treeNode4);
        treeNode4 = new javax.swing.tree.DefaultMutableTreeNode("Flyin Carpet");
        treeNode5 = new javax.swing.tree.DefaultMutableTreeNode("Ossomer");
        treeNode4.add(treeNode5);
        treeNode3.add(treeNode4);
        treeNode4 = new javax.swing.tree.DefaultMutableTreeNode("Gween Dwagon");
        treeNode5 = new javax.swing.tree.DefaultMutableTreeNode("Jack");
        treeNode4.add(treeNode5);
        treeNode3.add(treeNode4);
        treeNode4 = new javax.swing.tree.DefaultMutableTreeNode("Purple Dwagon");
        treeNode5 = new javax.swing.tree.DefaultMutableTreeNode("Slurp");
        treeNode4.add(treeNode5);
        treeNode3.add(treeNode4);
        treeNode4 = new javax.swing.tree.DefaultMutableTreeNode("Pink Dwagon");
        treeNode5 = new javax.swing.tree.DefaultMutableTreeNode("Glurp");
        treeNode4.add(treeNode5);
        treeNode3.add(treeNode4);
        treeNode4 = new javax.swing.tree.DefaultMutableTreeNode("Ginger");
        treeNode3.add(treeNode4);
        treeNode2.add(treeNode3);
        treeNode1.add(treeNode2);
        treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Cites");
        treeNode3 = new javax.swing.tree.DefaultMutableTreeNode("Gobwin Knob");
        treeNode4 = new javax.swing.tree.DefaultMutableTreeNode("Stanley the Tool");
        treeNode3.add(treeNode4);
        treeNode4 = new javax.swing.tree.DefaultMutableTreeNode("Georga Power");
        treeNode3.add(treeNode4);
        treeNode2.add(treeNode3);
        treeNode1.add(treeNode2);
        sideTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        treeScroll.setViewportView(sideTree);

        split2.setTopComponent(treeScroll);

        sideText.setEditable(false);
        sideText.setColumns(20);
        sideText.setRows(5);
        sideText.setText("Will Display Hex\nUnits\nTerrain Specifics");
        txtScroll.setViewportView(sideText);

        split2.setRightComponent(txtScroll);

        split1.setLeftComponent(split2);

        javax.swing.GroupLayout viewPortalLayout = new javax.swing.GroupLayout(viewPortal);
        viewPortal.setLayout(viewPortalLayout);
        viewPortalLayout.setHorizontalGroup(
            viewPortalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 612, Short.MAX_VALUE)
        );
        viewPortalLayout.setVerticalGroup(
            viewPortalLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 457, Short.MAX_VALUE)
        );

        split1.setRightComponent(viewPortal);
        viewPortal.getAccessibleContext().setAccessibleName("");
        viewPortal.getAccessibleContext().setAccessibleDescription("");

        jSplitPane1.setLeftComponent(split1);
        jSplitPane1.setRightComponent(textOut);

        file_Menu.setText("File");

        file_new.setText("New ErfWorld");
        file_new.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                file_newActionPerformed(evt);
            }
        });
        file_Menu.add(file_new);

        file_open.setText("Open");
        file_open.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                file_openActionPerformed(evt);
            }
        });
        file_Menu.add(file_open);

        file_save.setText("Save");
        file_save.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                file_saveActionPerformed(evt);
            }
        });
        file_Menu.add(file_save);

        file_saveAs.setText("SaveAs");
        file_saveAs.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                file_saveAsActionPerformed(evt);
            }
        });
        file_Menu.add(file_saveAs);

        file_exportPNG.setText("Export PNG");
        file_exportPNG.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                file_exportPNGActionPerformed(evt);
            }
        });
        file_Menu.add(file_exportPNG);

        file_exit.setText("Exit");
        file_exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                file_exitActionPerformed(evt);
            }
        });
        file_Menu.add(file_exit);

        menuBar.add(file_Menu);

        edit_Menu.setText("Edit");

        edit_addHexsToRadius.setText("Add Hexs to Radius");
        edit_addHexsToRadius.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                edit_addHexsToRadiusActionPerformed(evt);
            }
        });
        edit_Menu.add(edit_addHexsToRadius);

        edit_addHexByPicture.setText("Add Hexs By Picture");
        edit_addHexByPicture.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                edit_addHexByPictureActionPerformed(evt);
            }
        });
        edit_Menu.add(edit_addHexByPicture);

        menuBar.add(edit_Menu);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 820, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 492, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void file_openActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_file_openActionPerformed
        LucidWorld aErf = new LucidWorld();
        aErf.clear();
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int returnVal = fc.showOpenDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION){
            xmlFile = fc.getSelectedFile();
            LucidWorldParser ep = new LucidWorldParser();
            aErf = ep.parseFromFile(xmlFile);
            if(!aErf.isEmpty()){
                world = aErf;
                viewPortal.setErf(world);
            }        
        }
    }//GEN-LAST:event_file_openActionPerformed

    private void file_saveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_file_saveActionPerformed
        // TODO add your handling code here:
        if(xmlFile == null){
            JFileChooser fc = new JFileChooser();
            fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            int returnVal = fc.showSaveDialog(this);
            if(returnVal == JFileChooser.APPROVE_OPTION){
                xmlFile = fc.getSelectedFile();
                
            }else{
                return;
            }
        }
        saveFile();
    }//GEN-LAST:event_file_saveActionPerformed

    private void file_saveAsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_file_saveAsActionPerformed
        // TODO add your handling code here:
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int returnVal = fc.showSaveDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION){
            xmlFile = fc.getSelectedFile();
            saveFile();
        }

    }//GEN-LAST:event_file_saveAsActionPerformed

    private void edit_addHexsToRadiusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edit_addHexsToRadiusActionPerformed
        String rad = JOptionPane.showInputDialog(this, "ResizeMap", "Enter Radius");
        try{
            world.getBoard().resizeMap(Integer.parseInt(rad), LucidHexType.NULL_HEX);
            viewPortal.getViewOptions().reset();
        }catch(Exception e){
            
        }
    }//GEN-LAST:event_edit_addHexsToRadiusActionPerformed

    private void file_exportPNGActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_file_exportPNGActionPerformed
        // TODO add your handling code here:
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int returnVal = fc.showSaveDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION){
            File png = fc.getSelectedFile();
            BufferedImage bi = new BufferedImage(viewPortal.getSize().width, viewPortal.getSize().height, BufferedImage.TYPE_INT_ARGB); 
            Graphics g = bi.createGraphics();
            viewPortal.paint(g);  //this == JComponent
            g.dispose();
            try{
                ImageIO.write(bi,"png",png);
            }catch (Exception e) {}    
        
        }    
    }//GEN-LAST:event_file_exportPNGActionPerformed

    private void file_newActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_file_newActionPerformed
        world = new LucidWorld();
        world.setWorldTemplate(new ErfWorldDefaultTemplate());
        viewPortal.setErf(world);
    }//GEN-LAST:event_file_newActionPerformed

    private void file_exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_file_exitActionPerformed
        // TODO add your handling code here:
        this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
    }//GEN-LAST:event_file_exitActionPerformed

    private void edit_addHexByPictureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edit_addHexByPictureActionPerformed
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int returnVal = fc.showOpenDialog(this);
        if(returnVal == JFileChooser.APPROVE_OPTION){
            MaptoHexImport vmi = new MaptoHexImport(this, true);
            vmi.buildPictureView(world, fc.getSelectedFile());
            vmi.setVisible(true);
            this.repaint();
        }

    }//GEN-LAST:event_edit_addHexByPictureActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(GameMasterView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(GameMasterView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(GameMasterView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(GameMasterView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new GameMasterView().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu edit_Menu;
    private javax.swing.JMenuItem edit_addHexByPicture;
    private javax.swing.JMenuItem edit_addHexsToRadius;
    private javax.swing.JMenu file_Menu;
    private javax.swing.JMenuItem file_exit;
    private javax.swing.JMenuItem file_exportPNG;
    private javax.swing.JMenuItem file_new;
    private javax.swing.JMenuItem file_open;
    private javax.swing.JMenuItem file_save;
    private javax.swing.JMenuItem file_saveAs;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JTextArea sideText;
    private javax.swing.JTree sideTree;
    private javax.swing.JSplitPane split1;
    private javax.swing.JSplitPane split2;
    private javax.swing.JTextField textOut;
    private javax.swing.JScrollPane treeScroll;
    private javax.swing.JScrollPane txtScroll;
    private com.lucidhex.viewer.ViewPortal viewPortal;
    // End of variables declaration//GEN-END:variables

    private void saveFile() {
        LucidWorldParser ep = new LucidWorldParser();
        ep.parseToFile(xmlFile, world);
    }
}
